#include "chat.h"
#include <QWidget>
#include "ui_chat.h"
#include <QDebug>
#include <QLabel>
#include <QScrollBar>
#include "../main/mainwindow.h"
#include "../../models/usermodel.h"

Chat::Chat(QWidget *parent)
    :QWidget(parent)
    ,ui(new Ui::Chat)
{
    ui->setupUi(this);
}


void Chat::styleSelf(){
    //左侧scroll窗口
    ui->scrollArea->setGeometry(0, 0, MainWindow::WINDOW_LEFT_SCROLL_WIDTH + 20, MainWindow::WINDOW_BODY_HEIGHT - 17);
//    ui->scrollArea->setStyleSheet("QScrollBar{width:8px;border-radius:4px;border:0px solid #7e7e7e;}"
//                                  "QScrollBar::handle{width:16px;border-radius:4px;border:0px solid #7e7e7e;background-color:#7e7e7e}"
//                                  "QScrollBar::handle:hover{width:16px;border-radius:4px;border:0px solid #7e7e7e;background-color:#7e7e7e}");
    //左侧scroll幕布
    ui->scrollAreaWidgetContents->setMinimumHeight(MainWindow::WINDOW_BODY_HEIGHT - 20);

    //右侧banner
    this->drawChatBanner("请点击左侧聊天");
    //右侧scroll也就是聊天记录
    this->drawChatScroll();
    //右侧聊天菜单
    this->drawChatMenu();
    //输入框
    this->drawChatTextarea();
    //聊天记录demo
//    this->chatListHistoryDemo();
    this->initChatList();
}


/*********************************************顶部begin****************************************/
/**
 * @brief Chat::addUnreadNum 新增未读数
 * @param uid
 * @param num
 */
void Chat::addUnreadNum(int uid, int num){
    if(this->userChatUnreadNumMap.contains(uid)){
        this->userChatUnreadNumMap[uid] += num;
    }else{
        this->userChatUnreadNumMap.insert(uid, num);
    }
}

QString Chat::getUnreadNumByUidStr(int uid){
    int userTotalNum = 0;
    QString userTotalNumStr = "";
    if(this->userChatUnreadNumMap.contains(uid)){
        userTotalNum = this->userChatUnreadNumMap[uid];
    }

    if(userTotalNum >= 100){
        userTotalNumStr = "99+";
    }else{
        userTotalNumStr = QString::number(userTotalNum);
    }

    return userTotalNumStr;
}

void Chat::clearUnreadNum(int uid){
    if(this->userChatUnreadNumMap.contains(uid)){
        this->userChatUnreadNumMap[uid] = 0;
    }

}

QString Chat::getAllUnreadTotalNumStr(){
    int totalNum = 0;
    QString totalNumStr = "";
    QMap<int, int>::iterator it;
    for (it = this->userChatUnreadNumMap.begin(); it != this->userChatUnreadNumMap.end(); it++) {
        totalNum += it.value();
    }

    if(totalNum >= 100){
        totalNumStr = "99+";
    }else{
        totalNumStr = QString::number(totalNum);
    }

    return totalNumStr;
}

/*********************************************顶部end****************************************/



/*********************************************左侧begin****************************************/

/**
 * @brief Chat::setCurrentClickedItem 设置当前选中的用户
 * @param user
 */
void Chat::setCurrentClickedItem(ItemButton* item){
    this->currentClickedItem = item;
}

ItemButton* Chat::getCurrentClickedItem(){
    return this->currentClickedItem;
}

/**
 * @brief Chat::addOneChatItem 左侧新增一个聊天对象
 * @param uid
 * @param item
 */
void Chat::addOneChatItem(int uid, ItemButton* item){
    //新增左侧聊天人员列表
    if(!this->userChatList.contains(uid)){
        this->userChatList[uid] = item;
    }

    //初始化聊天记录
    QVector<eachChatMsgStruct> tmp;
    if(!this->userChatHistory.contains(uid)){
        this->userChatHistory[uid] = tmp;
    }
}

/**
 * @brief Chat::isExistItem 判断左侧是否有该聊天对象
 * @param uid
 * @return
 */
bool Chat::isExistItem(int uid){
    if(this->userChatList.contains(uid)){
        return true;
    }

    return false;
}

/**
 * @brief Chat::refreshItemUnreadNum 刷新左侧某个聊天对象的未读数
 * @param uid
 * @param numStr
 */
void Chat::refreshItemUnreadNum(int uid, QString numStr){
    if(this->isExistItem(uid)){
        this->userChatList[uid]->refreshChatUnreadNum(numStr);
    }
}

/**
 * @brief Chat::clickItemButtonEventForChatPage 点击item事件
 * @param item
 */
void Chat::clickItemButtonEventForChatPage(ItemButton *item){
    //获取上次点击的item
    ItemButton* lastClickedItem = this->getCurrentClickedItem();
    //设置chat 当前选中的对象
    this->setCurrentClickedItem(item);

    //修改点击样式
    if(lastClickedItem != nullptr && item->userProfile.uid != lastClickedItem->userProfile.uid){
        //上一个被点击中的样式还原
        lastClickedItem->setStyleSheet("QLabel{background-color:#fdfdfd}");
    }

    //重新赋值右侧的banner昵称
    this->drawChatBanner(item->userProfile.username);
    //修改点击样式
    item->setStyleSheet("QLabel{background-color:#f1f1f1}");
    //重新赋值右侧的聊天内容
    this->refreshUserChatHistory();

    //刷新未读红点
    this->refreshItemUnreadNum(item->userProfile.uid, "");

    //清空未读红点
    this->clearUnreadNum(item->userProfile.uid);

    //刷新全局chat红点
    MainWindow *mainPtr = (MainWindow*)parent()->parent()->parent();
    QString allUnreadTotalNumStr = mainPtr->chat->getAllUnreadTotalNumStr();
    mainPtr->refreshAllUnreadNum(allUnreadTotalNumStr);
}

//新增一个左侧scroll的item元素
ItemButton* Chat::addLeftScrollItem(responseUserInfo userProfile, QString unreadNumStr){
    int uid = userProfile.uid;

    //判断左侧是否存在该聊天对象
    if(this->isExistItem(userProfile.uid)){
        this->userChatList[uid]->refreshChatUnreadNum(unreadNumStr);
        return this->userChatList[uid];
    }else{
        ItemButton *itemButton = new ItemButton(ui->scrollAreaWidgetContents);
        itemButton->setUserProfile(userProfile);
        itemButton->setUid(userProfile.uid);
        itemButton->setNickanme(userProfile.username);
        itemButton->setUserProfile(userProfile);
        itemButton->setFixedSize(MainWindow::WINDOW_LEFT_SCROLL_WIDTH, itemButton->defaultHeight);
        itemButton->setVisible(true);
        itemButton->setUseType(ItemButton::USE_TYPE_FOR_CHAT);
        itemButton->draw();
        itemButton->refreshChatUnreadNum(unreadNumStr);

        //新增到uids的记录，此uids用于删除
        this->addOneChatItem(userProfile.uid, itemButton);

        //@todo链接点击事件@todo，点击后展示右侧聊天界面，实现用户之间切换
        //connect(itemButton, &QPushButton::clicked, itemButton, &ItemButton::clickButtonForChat);//已被重写在itembutton

        this->scrollLayout->addWidget(itemButton);
        this->scrollLayout->setDirection(QBoxLayout::BottomToTop);
        this->scrollLayout->setSpacing(0);
        this->scrollLayout->setMargin(0);
        this->scrollLayout->setSizeConstraint(QLayout::SetFixedSize);
        ui->scrollAreaWidgetContents->setLayout(this->scrollLayout);

        return itemButton;
    }

}
/*********************************************左侧end****************************************/


/*********************************************右侧begin****************************************/
void Chat::drawChatBanner(QString nickname){
    this->chatBanner->setGeometry(MainWindow::WINDOW_LEFT_SCROLL_WIDTH + 20,
                                  0,
                                  MainWindow::WINDOW_BODY_WIDTH,
                                  MainWindow::WINDOW_CHAT_BANNER_HEIGHT);
    this->chatBanner->setStyleSheet("background-color:#fdfdfd");
    this->chatBanner->setText("   " + nickname);
    this->chatBanner->show();
}

void Chat::drawChatScroll(){
    ui->scrollArea_2->setGeometry(MainWindow::WINDOW_LEFT_SCROLL_WIDTH + 20,
                                  MainWindow::WINDOW_CHAT_BANNER_HEIGHT,
                                  MainWindow::WINDOW_BODY_WIDTH - 20,
                                  MainWindow::WINDOW_CHAT_SCROLL_HEIGHT);
    ui->scrollArea_2->setStyleSheet("QScrollBar{width:8px;border-radius:4px;border:0px solid #7e7e7e;}"
                                  "QScrollBar::handle{width:16px;border-radius:4px;border:0px solid #7e7e7e;background-color:#7e7e7e}"
                                  "QScrollBar::handle:hover{width:16px;border-radius:4px;border:0px solid #7e7e7e;background-color:#7e7e7e}");
    ui->scrollAreaWidgetContents_2->setStyleSheet("background-color:#fdfdfd");
    ui->scrollAreaWidgetContents_2->setMinimumHeight(100);
}

void Chat::drawChatMenu(){
    this->chatMenu->setGeometry(MainWindow::WINDOW_LEFT_SCROLL_WIDTH + 20,
                                MainWindow::WINDOW_CHAT_BANNER_HEIGHT + MainWindow::WINDOW_CHAT_SCROLL_HEIGHT,
                                MainWindow::WINDOW_BODY_WIDTH,
                                MainWindow::WINDOW_CHAT_MENU_HEIGHT);
    this->chatMenu->setStyleSheet("background-color:#fdfdfd");
    this->chatMenu->show();
}

void Chat::drawChatTextarea(){
    this->chatEdit->setGeometry(MainWindow::WINDOW_LEFT_SCROLL_WIDTH + 20,
                              MainWindow::WINDOW_CHAT_BANNER_HEIGHT + MainWindow::WINDOW_CHAT_SCROLL_HEIGHT + MainWindow::WINDOW_CHAT_MENU_HEIGHT,
                              MainWindow::WINDOW_BODY_WIDTH,
                              MainWindow::WINDOW_BODY_HEIGHT - MainWindow::WINDOW_CHAT_BANNER_HEIGHT - MainWindow::WINDOW_CHAT_SCROLL_HEIGHT - MainWindow::WINDOW_CHAT_MENU_HEIGHT);
    this->chatEdit->setStyleSheet("background-color:#fdfdfd");
}


//@todo已经有回车事件了
void Chat::chatListHistoryDemo(){
    QVBoxLayout* layout = new QVBoxLayout(this);

    for(int i = 0; i< 10; i++){
        QLabel* label = new QLabel();
        label->setFixedSize(MainWindow::WINDOW_BODY_WIDTH-40, 30);
        label->setText("haha哈哈");
        label->setAlignment(Qt::AlignLeft);
        layout->addWidget(label);
    }

    for(int i = 0; i< 10; i++){
        QLabel* label = new QLabel();
        label->setFixedSize(MainWindow::WINDOW_BODY_WIDTH-40, 30);
        label->setText("haha哈哈");
        label->setAlignment(Qt::AlignRight);
        layout->addWidget(label);
    }

    layout->setSpacing(0);
    layout->setMargin(0);
    layout->setSizeConstraint(QLayout::SetFixedSize);
    ui->scrollAreaWidgetContents_2->setLayout(layout);

}

void Chat::initChatList(){
    if(this->chatListLayout == nullptr){
        this->chatListLayout = new QVBoxLayout(this);
    }

    this->chatListLayout->setSpacing(0);
    this->chatListLayout->setMargin(0);
    this->chatListLayout->setSizeConstraint(QLayout::SetFixedSize);
    ui->scrollAreaWidgetContents_2->setLayout(this->chatListLayout);
}


/**
 * @brief Chat::sendMsg发送消息
 * @param content
 */
void Chat::sendMsg(QString content){
    this->addMyChat(content, true);

    MainWindow *mainPtr = (MainWindow*)parent()->parent()->parent();
    //发送
    UserModel* userModel = UserModel::NewInstance();
    requestChatStruct req;
    req.uid = mainPtr->uid;
    req.beuid = this->getCurrentClickedItem()->userProfile.uid;
    req.msg = content.toStdString();

    userModel->sendMsg(req);
}

/**
 * @brief Chat::apiChatCallback发送消息回调(判断是否发送成功)
 * @param code
 * @param msg
 */
void Chat::apiChatCallback(int code, QString msg){
    if(code != ResponseStruct::XIAOH_ROUTE_CODE_SUCCESS){
        //发送失败
        QString content = "发送失败：" + msg;
        this->addMyChat(content, true);
    }
}

/**
 * @brief Chat::addMyChat 只是把我发送的内容显示在聊天框
 * @param content
 */
void Chat::addMyChat(QString content, bool recordData){
    QLabel* label = new QLabel();
    label->setFixedSize(MainWindow::WINDOW_BODY_WIDTH-40, 30);
    label->setText(content);
    label->setAlignment(Qt::AlignRight);
    this->chatListLayout->addWidget(label);

    //把滚动条移动到最下面
    int max = this->ui->scrollArea_2->verticalScrollBar()->maximum();
    this->ui->scrollArea_2->verticalScrollBar()->setValue(max);

    //记录到 userChatListHistory，用于各个玩家切换
    if(recordData){
        eachChatMsgStruct msgStruct;
        msgStruct.msgType = this->MSG_TYPE_MY;
        msgStruct.content = content;
        this->userChatHistory[this->getCurrentClickedItem()->userProfile.uid].append(msgStruct);
    }
}

/**
 * @brief Chat::addPairChat 把对方发送的消息显示在聊天框
 * @param content
 */
void Chat::addPairChat(int uid, QString content, bool recordData){
    if(this->getCurrentClickedItem() != nullptr && uid == this->getCurrentClickedItem()->userProfile.uid){
        QLabel* label = new QLabel();
        label->setFixedSize(MainWindow::WINDOW_BODY_WIDTH-40, 30);
        label->setText(content);
        label->setAlignment(Qt::AlignLeft);
        this->chatListLayout->addWidget(label);
        //把滚动条移动到最下面
        int max = this->ui->scrollArea_2->verticalScrollBar()->maximum();
        this->ui->scrollArea_2->verticalScrollBar()->setValue(max);
    }

    //记录到 userChatListHistory，用于各个玩家切换
    if(recordData){
        eachChatMsgStruct msgStruct;
        msgStruct.msgType = this->MSG_TYPE_PAIR;
        msgStruct.content = content;
        this->userChatHistory[uid].append(msgStruct);
    }
}

void Chat::refreshUserChatHistory(){
    delete this->chatListLayout;
    this->chatListLayout = nullptr;
//    ui->scrollAreaWidgetContents_2->setLayout(nullptr);
    this->initChatList();

    int len = this->userChatHistory[this->getCurrentClickedItem()->userProfile.uid].length();

    if(len > 0){
        for(int i=0; i<len; i++){
            eachChatMsgStruct msgStruct;
            msgStruct = this->userChatHistory[this->getCurrentClickedItem()->userProfile.uid][i];
            if(msgStruct.msgType == this->MSG_TYPE_MY){
                this->addMyChat(msgStruct.content, false);
            }else if (msgStruct.msgType == this->MSG_TYPE_PAIR) {
                this->addPairChat(this->getCurrentClickedItem()->userProfile.uid, msgStruct.content, false);
            }else if (msgStruct.msgType == this->MSG_TYPE_SYS) {
                this->addMyChat(msgStruct.content, false);
            }

        }

    }else{
        this->addMyChat("", true);//必须要add 一个widget进去，不然聊天记录框不会清除
    }
}




/*********************************************右侧end****************************************/
